// src/pages/ArticleDetail.tsx
import { Tag } from "antd";
import { useEffect, useState } from "react";
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";
import { history, useMatch } from "umi";

interface ArticleDetailData {
  id: string;
  title: string;
  author: string;
  date: string;
  readingTime: string;
  tags: string[];
  content: string;
}
// 提取标题
const extractHeadings = (markdown: string | undefined) => {
  if (!markdown) return [];
  const headingRegex = /^#{1,6}\s+(.+)$/gm;
  const headings = [];
  let match;
  while ((match = headingRegex.exec(markdown)) !== null) {
    const [fullMatch] = match;
    const level = fullMatch.indexOf(" ") - 1; // #数量
    const text = match[1];
    const id = text.trim().toLowerCase().replace(/\s+/g, "-");
    headings.push({ level, text, id });
  }
  return headings;
};

const ArticleDetail = () => {
  const match = useMatch("/detail/:id");
  const articleId = match?.params.id;
  const [data, setData] = useState<ArticleDetailData | null>(null);
  const [loading, setLoading] = useState(true);
  const headings = extractHeadings(data?.content);

  useEffect(() => {
    if (!articleId) return;
    const fetchDetail = async () => {
      try {
        // 这里指向本地 mock 文件，实际项目可替换为真实 API
        const resp = await fetch(`/api/detail`);
        const json: ArticleDetailData = await resp.json();
        setData(json);
      } catch (err) {
        console.error("获取文章详情失败", err);
      } finally {
        setLoading(false);
      }
    };
    fetchDetail();
  }, [articleId]);

  const handleClick = () => {
    // 跳转到编辑页面
    history.push(`/edit/${articleId}`);
  };

  if (loading) {
    return <div className="text-center py-10">加载中...</div>;
  }
  if (!data) {
    return <div className="text-center py-10 text-red-500">未找到该文章</div>;
  }

  return (
    <div className="flex flex-row bg-gray-100 min-h-screen">
      <div className="w-3/5 mx-auto p-6 bg-white shadow-md rounded-lg min-h-full">
        {/* 标题 */}
        <div className="w-full flex align-middle justify-between">
          <h1 className="text-3xl font-bold mb-4">{data.title}</h1>
          <span className="text-cyan-300 cursor-pointer" onClick={handleClick}>
            编辑文章
          </span>
        </div>

        {/* 元信息 */}
        <div className="flex items-center text-sm text-gray-500 mb-6">
          <span>作者：{data.author}</span>
          <span className="mx-2">|</span>
          <span>日期：{data.date}</span>
          <span className="mx-2">|</span>
          <span>阅读：{data.readingTime}</span>
        </div>

        {/* 标签 */}
        <div className="mb-6">
          {data.tags.map((tag) => (
            <Tag key={tag}>{tag}</Tag>
          ))}
        </div>

        {/* 正文内容 */}
        <article className="prose prose-lg">
          <ReactMarkdown
            children={data.content}
            components={{
              h1: ({ node, ...props }) => (
                <h1
                  id={String(props.children).replace(/\s+/g, "-").toLowerCase()}
                  {...props}
                />
              ),
              h2: ({ node, ...props }) => (
                <h2
                  id={String(props.children).replace(/\s+/g, "-").toLowerCase()}
                  {...props}
                />
              ),
              h3: ({ node, ...props }) => (
                <h3
                  id={String(props.children).replace(/\s+/g, "-").toLowerCase()}
                  {...props}
                />
              ),
            }}
            remarkPlugins={[remarkGfm]}
            rehypePlugins={[rehypeRaw]}
          />
        </article>
      </div>
      <div className="w-1/5 p-6 sticky top-20 h-screen overflow-auto bg-white shadow-md rounded-lg ml-4">
        <div className="font-bold mb-4">目录</div>
        <ul className="space-y-2">
          {headings.map((heading, index) => (
            <li key={index} className={`ml-${(heading.level - 1) * 4}`}>
              <a
                href={`#${heading.id}`}
                className="text-gray-600 hover:text-black text-sm block"
              >
                {heading.text}
              </a>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};
export default ArticleDetail;
